import {
	getPicture
} from '@/api/doc.js' //获取图片
import path from "@/config/path.js"
import obj from "@/config/index"
	import {
		getToken
	} from '@/utils/auth.js'
	import {
		uploadFile
	} from '@/utils/request'
/**
 * 获取到docId中的图片并且拼成网络路径格式
 * @param {Number} docId
 * @return {String} //拼好的网络路径格式(base64格式的编码)
 */

const DefaultErrorImgPath = '/subpackage-emergency/static/img-fail.png'

export async function getImageBase64(docId) {
	if(!docId) {
		console.error('没有docId');
		return
	}
	const res = await getPicture({docId})
	const base64ImgList = []
	const taskDownloadImage2Base64 = res.result.map(async attch => {
		base64ImgList.push({
			id: attch.id
		})
		return urlTobase64(`${path.IMG_FILE_URL + attch.fileName}`)

	})
	const taskResults = await Promise.all(taskDownloadImage2Base64)
	taskResults.forEach((r, idx) => base64ImgList[idx].url = r)
	return base64ImgList
}

export async function downLoadImage(docId, saveFile2Local=true) {
	if(!docId) {
		console.error('没有docId');
		return
	}
	const res = await getPicture({docId})
	const base64ImgList = []
	const taskDownloadImage2Base64 = res.result.map(async attch => {
		base64ImgList.push({
			id: attch.id
		})
		return downLoadFile(`${path.IMG_FILE_URL + attch.fileName}`, saveFile2Local)

	})
	const taskResults = await Promise.all(taskDownloadImage2Base64)
	taskResults.forEach((r, idx) => base64ImgList[idx].url = r)
	return base64ImgList
}
//下载视频
export async function downLoadVideo(videoDocId, saveFile2Local=true) {
	if(!videoDocId) {
		console.error('没有videoDocId');
		return
	}
	const res = await getPicture({docId:videoDocId})
	const videoArr = []
	const taskDownloadVideo = res.result.map(async attch => {
		videoArr.push({
			id: attch.id
		})
		return downLoadFile(`${path.VIDEO_URL + attch.fileName}`, saveFile2Local)

	})
	const taskResults = await Promise.all(taskDownloadVideo)
	taskResults.forEach((r, idx) => videoArr[idx].url = r)
	return videoArr
}


export async function cacheImageWithBase64(docIds=[]) {
	try{
		let resAll = await Promise.all(docIds.map(docId=>getPicture({docId})))
		resAll = resAll
			.map(r=>r.result)
			.flat()
			.map(({id, docInfoId, fileName})=>({id, docInfoId, fileName}))
		let base64All = await Promise.all(
			resAll.map(({id, docInfoId, fileName}) =>
				urlTobase64(`${path.IMG_FILE_URL + fileName}`)
			)
		)
		resAll.forEach((img,idx)=>img.url=base64All[idx])
		return resAll
	}catch(e){
		console.error('cacheImageWithBase64 error', e)
	}
}

/**
 * @param {Object} url 传入url返回base64
 */
export function urlTobase64(url) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: 'GET',
			responseType: 'arraybuffer',
			fail: error => {
				console.error('urlTobase64() error', error);
				reject(error);
			},
			success: async res => {
				let base64 = uni.arrayBufferToBase64(res.data);
				base64 = 'data:image/jpeg;base64,' + base64;
				resolve(base64);
			}
		})
	})
}


/**
 * @param {Object} url 传入url返回base64
 */
export function downLoadFile(url, saveFile2Local) {
	if(!saveFile2Local) return Promise.resolve(DefaultErrorImgPath)
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: url,
			fail: error => {
				console.error('downLoadFile() error', error);
				reject(error);
			},
			success: res1 => {
				saveFile(res1.tempFilePath)
				.then(res2 => {
					// console.warn('res1',res1.tempFilePath);
					// console.warn('res2',res2);
					resolve(res2)
				})
				.catch(error => {
					console.error('saveFile() error', error);
					reject(error);
				})
			}
		})
	})
}

/**
 * @param {Object} path 传入本地路径返回base64图片
 */
export function localPathToBase64(path) {
	console.log(path,'默认path');
	//如果是拍摄上传需要自己拼接路径
	if(path.startsWith("_doc")){
		path = 'file://' +  plus.io.convertLocalFileSystemURL(path);
	}
	
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			path,
			function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader()
					fileReader.readAsDataURL(file)
					fileReader.onloadend = function(evt) {
						let base64 = evt.target.result.split(",")[1]
						resolve('data:image/jpeg;base64,' + base64)
					}
				})
			},
			function(err) {
				console.error(err);
				reject(err)
			}
		)
	})
}


export function uploadImageFromBase64({dataList, docId,base64List}) {
	return new Promise((resolve, reject) => {
		let formData = {
		        token:getToken(),
				dataList,
				base64List
		    }
		if(docId){
			formData.docId = docId
		}
		uni.request({
			method:'POST',
		    url: obj.BASE_URL + 'composite/picture/addPictureText/pitch',
		    data: formData,
		    success: (res) => {
		        resolve(res.data)
		    },
			fail:(error)=> {
				console.error(error);
				reject(error)
			},
			complete:() => {
				console.log('uploadImageFromBase64 complete');
			}
		});

	})
}
// export const uploadFile = ({url, formData = {}, files = [], isOffline = false})
export async function uploadVideo({docId,videosList}) {
		videosList = videosList.map(it => ({
				name: "attach",
				uri: it
		}))
		let formData = {}
		if(docId){
			formData.docId = docId
		}
		console.log(formData,videosList,'传进来的数组');
		// http://172.168.20.24:5027/cdsa-web/rest/doc/uploadDoc
		return await uploadFile({
			url: 'rest/doc/uploadDoc',
			formData,
			files:videosList,
			isOffline:true
		})
}

export function saveFile(url) {
	return new Promise((resolve, reject) => {
		uni.saveFile({
		      tempFilePath: url,
		      success: function (res) {
				resolve(res.savedFilePath)
		      },
			  fail: error => {
			  	console.error('saveFile() error', error);
			  	reject(error);
			  }
		    })
	})
}

